#!/usr/bin/node

let items = ['apple','pear','orange'];
const fs = require('fs'),
      http = require('http'),
      url = require('url'),
      qs = require('querystring');

function genPage(){ 
  let html = fs.readFileSync('./template.html').toString('utf8');
  html = html.replace('$',items.map(i=>'<li>'+i+'</li>').join('\n'));

  return html;
}

http.createServer((req,res)=>{
  let addr = url.parse(req.url);
  if(addr.pathname!=='/'){
    res.statusCode = 404;
    res.setHeader('Content-Type','text/html');
    res.end('<h1>Not Found 404</h1>');
    return ;
  }

  let data = '';
  req.on('data',chunk => data += chunk);
  req.on('end',()=>{
    let item =  qs.parse(data).item;
    if(item !== '' && typeof(item) !== 'undefined') items.push(item);
  
    res.writeHead(200, {
      'Content-Type': 'text/html',
      'Content-Lenght': Buffer.byteLength(genPage())  
    });

    res.end(genPage());
  })

}).listen(8080);
